<script setup lang="ts">
import { watch } from "vue";
import { ref } from "vue";
import { getApplyDetail } from "@/api/apply";
import ButtonTrans from "./buttons/ButtonTrans.vue";
import { reason } from "@/utils";
import { unit } from "@/utils/product";
import { M10Approve } from "@/api/apply";
import { dayjs, ElMessage } from "element-plus";
import { segmentCheckPatch } from "@/api/apply";

const props = defineProps(["docid", "isMounted"]);
const emits = defineEmits(["returnApply"]);
//異步獲取數據時會出現渲染錯誤。為防止渲染錯誤，給定一個空值。
const applyFormItems = ref<applyForm[]>([
  {
    docid: "",
    current_flow: 0,
    material_origina: "",
    current_flow_phase: "",
    material_product: "",
    replace_reason: "",
    replace_comments: "",
    material_replacea: "",
    unit: "",
    amount: 0,
    start_time: "",
    apply_seq: 0,
  },
]);

export interface applyForm {
  docid: string;
  current_flow: number;
  material_origina: string;
  material_replacea: string;
  current_flow_phase: string;
  material_product: string;
  replace_reason: string;
  replace_comments: string;
  unit: string;
  amount: number;
  start_time: string;
  apply_seq: number;
}

watch(
  () => props.isMounted,
  () => {
    if (props.isMounted) {
      getApplyDetail(props.docid).then((res: any) => {
        applyFormItems.value.pop();
        res.forEach((item: applyForm) => {
          item.start_time = dayjs(item.start_time).format("YYYY-MM-DD")
          applyFormItems.value.push(item);
        });
      });
    }
  }
);

function returnApply() {
  applyFormItems.value = [];
  emits("returnApply");
}

function applySend() {
  //不為空判定
  let segments: Array<string> = [];
  applyFormItems.value.forEach((item: applyForm) => {
    if (
      item.material_origina === "" ||
      item.material_replacea === "" ||
      item.material_product === "" ||
      item.material_replacea === "" ||
      item.unit === "" || item.amount === 0 ||
      item.start_time === ""
    ) {
      ElMessage.error("輸入有空數據，請重試");
      return false;
    }
    if(item.material_origina === item.material_replacea){
      ElMessage.error(`原料號:${item.material_origina} 與替代料號:${item.material_replacea}相同，無法送出！`);
      return false;
    }
    segments.push(item.material_origina);
    segments.push(item.material_replacea);
  });
  segmentCheckPatch(JSON.stringify(segments)).then((res: any) => {
    let data = res[0];
    for (let i = 0; i < segments.length; i++) {
      let propname = "count_" + (i + 1);
      if (data[propname] === 0) {
        ElMessage.error(`查無料號：${segments[i]}`);
        return false;
      }
    }
    let docinfo = {
      docid: props.docid,
      current_flow: applyFormItems.value[0].current_flow,
      username: localStorage.getItem("username")?.toString(),
      comments: "",
      approve: "Y",
    };
    M10Approve(
      JSON.stringify(docinfo),
      JSON.stringify(applyFormItems.value)
    ).then((res) => {
      if (res) {
        ElMessage.success("送出成功!");
        returnApply();
      }
    });
  });
  // if (flag) {
  //   return false;
  // }
  // let docinfo = {
  // docid: props.docid,
  // current_flow: applyFormItems.value[0].current_flow,
  // username: localStorage.getItem("username")?.toString(),
  //   comments: "",
  //   approve: "Y",
  // };
  // M10Approve(
  //   JSON.stringify(docinfo),
  //   JSON.stringify(applyFormItems.value)
  // ).then((res) => {
  //   if (res) {
  //     ElMessage.success("送出成功!");
  //     returnApply();
  //   }
  // });
}
</script>

<template>
  <div v-if="props.docid" class="input-box-apply">
    <el-row style="padding-top: 7px; font-weight: bold">
      <el-col :span="16" style="text-align: center">
        <el-text>單號：</el-text>
        <el-text style="font-weight: 600">{{ props.docid }}</el-text>
        <el-text style="margin-left: 50px">當前流程：</el-text>
        <el-text style="font-weight: 600">{{
          applyFormItems[0].current_flow_phase
        }}</el-text>
      </el-col>
      <el-col :span="4">
        <ButtonTrans @click="applySend" text="確認送出"></ButtonTrans>
      </el-col>
      <el-col :span="4">
        <ButtonTrans @click="returnApply" text="返回申請"></ButtonTrans>
      </el-col>
    </el-row>
    <div class="apply-grid">
      <el-table
        :data="applyFormItems"
        style="width: 92%; margin: 1% auto; border: 1px solid grey"
        height="550"
        stripe
      >
        <!-- 原料號 -->
        <el-table-column align="center" fixed label="原料號" :width="160">
          <template #default="scope">
            <el-input
              v-model="applyFormItems[scope.$index].material_origina"
            ></el-input>
          </template>
        </el-table-column>
        <!-- 替換料號 -->
        <el-table-column align="center" label="替換料號" :width="160">
          <template #default="scope">
            <el-input
              v-model="applyFormItems[scope.$index].material_replacea"
            ></el-input>
          </template>
        </el-table-column>
        <!-- 成品號 -->
        <el-table-column align="center" label="成品號" :width="165">
          <template #default="scope">
            <el-input disabled
              v-model="applyFormItems[scope.$index].material_product"
            ></el-input>
          </template>
        </el-table-column>
        <!-- 替換原因 -->
        <el-table-column align="center" label="替換原因" :width="120">
          <template #default="scope">
            <el-select v-model="applyFormItems[scope.$index].replace_reason">
              <el-option
                v-for="list in reason"
                :key="list.code"
                :value="list.desc"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- 單位 -->
        <el-table-column align="center" label="單位" :width="80">
          <template #default="scope">
            <el-select v-model="applyFormItems[scope.$index].unit">
              <el-option
                v-for="list in unit"
                :key="list.code"
                :value="list.unit"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
         <!-- 數量 -->
         <el-table-column align="center" label="數量" :width="162">
          <template #default="scope">
            <el-input-number v-model="applyFormItems[scope.$index].amount" :min="0"></el-input-number>
          </template>
        </el-table-column>
         <!-- 開始時間 -->
         <el-table-column align="center" label="開始時間" :width="160">
          <template #default="scope">
            <el-date-picker v-model="applyFormItems[scope.$index].start_time" value-format="YYYY-MM-DD"></el-date-picker>
          </template>
        </el-table-column>
        <!-- 替換備註 -->
        <el-table-column align="center" label="替換備註" :width="150">
          <template #default="scope">
            <el-input
              v-model="applyFormItems[scope.$index].replace_comments"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style>
.input-box-apply {
  width: 100%;
  /* padding-top: 20px; */
  /* font-family: "Courier New", Courier, monospace; */
  line-height: 32px;
  min-height: 600px;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0px 10px 10px 0px rgba(30, 30, 30, 0.7);
  margin: 20px auto;
  min-height: 600px;
  border-radius: 20px;
  overflow: hidden;
}
</style>
